#include "bsp_usart.h"

UART_HandleTypeDef Uart2_Handle;

/**
 * @brief       串口X初始化函数
 * @param       baudrate: 波特率, 根据自己需要设置波特率值
 * @note        注意: 必须设置正确的时钟源, 否则串口波特率就会设置异常.
 * @retval      无
 */
void USART2_Config(void)
{

  Uart2_Handle.Instance = USART2;
  Uart2_Handle.Init.BaudRate = 115200UL;
  Uart2_Handle.Init.WordLength = UART_WORDLENGTH_8B;
  Uart2_Handle.Init.StopBits = UART_STOPBITS_1;
  Uart2_Handle.Init.Parity = UART_PARITY_NONE;
  Uart2_Handle.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  Uart2_Handle.Init.Mode = UART_MODE_TX_RX;
  /*使能串口 */
  HAL_UART_Init(&Uart2_Handle);
  /*使能串口接收断 */
}

/**
 * @brief       UART底层初始化函数
 * @param       huart: UART句柄类型指针
 * @note        此函数会被HAL_UART_Init()调用
 *              完成时钟使能，引脚配置，中断配置z
 * @retval      无
 */
void HAL_UART_MspInit(UART_HandleTypeDef *UartHandle)
{

  if (UartHandle->Instance == USART2)
  {
    GPIO_InitTypeDef Uart_GPIO_InitConfig;

    /*USART1时钟使能*/
    UART_Rx_GPIO_CLK_ENABLE();
    UART_Tx_GPIO_CLK_ENABLE();
    __HAL_RCC_USART2_CLK_ENABLE();

    Uart_GPIO_InitConfig.Pin = UART_Tx_GPIO_PIN;
    Uart_GPIO_InitConfig.Mode = GPIO_MODE_AF_PP;
    Uart_GPIO_InitConfig.Pull = GPIO_PULLUP;
    Uart_GPIO_InitConfig.Speed = GPIO_SPEED_FREQ_HIGH;

    Uart_GPIO_InitConfig.Alternate = GPIO_AF2_USART2; /* USART2复用功能 */
    HAL_GPIO_Init(UART_Tx_GPIO_PORT, &Uart_GPIO_InitConfig);

    Uart_GPIO_InitConfig.Pin = UART_Rx_GPIO_PIN;
    Uart_GPIO_InitConfig.Alternate = GPIO_AF2_USART2; /* USART2复用功能 */
    HAL_GPIO_Init(UART_Rx_GPIO_PORT, &Uart_GPIO_InitConfig);


    HAL_NVIC_SetPriority(USART2_IRQn, 0, 1); /* 抢占优先级0，子优先级1 */
    HAL_NVIC_EnableIRQ(USART2_IRQn);         /* 使能USART1中断通道 */
  }
}

///* 加入以下代码, 支持printf函数 */
#if (defined(__CC_ARM)) || (defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050))
/**
 * @brief  writes a character to the usart
 * @param  ch
 *         *f
 * @retval the character
 */
int fputc(int ch, FILE *f)
{
  /* Send a byte to USART */
  HAL_UART_Transmit(&Uart2_Handle, (uint8_t *)&ch, 1, 1000);

  return (ch);
}

/**
 * @brief  get a character from the usart
 * @param  *f
 * @retval a character
 */
int fgetc(FILE *f)
{
  int ch;
  HAL_UART_Receive(&Uart2_Handle, (uint8_t *)&ch, 1, 1000);
  return (ch);
}

#elif defined(__ICCARM__)
/**
 * @brief  writes a character to the usart
 * @param  ch
 *         *f
 * @retval the character
 */
int putchar(int ch)
{
  /* Send a byte to USART */
  HAL_UART_Transmit(&DebugUartHandle, (uint8_t *)&ch, 1, 1000);

  return (ch);
}
#elif defined(__GNUC__)
/**
 * @brief  writes a character to the usart
 * @param  ch
 * @retval the character
 */
int __io_putchar(int ch)
{
  /* Send a byte to USART */
  HAL_UART_Transmit(&DebugUartHandle, (uint8_t *)&ch, 1, 1000);

  return ch;
}

int _write(int file, char *ptr, int len)
{
  int DataIdx;
  for (DataIdx = 0; DataIdx < len; DataIdx++)
  {
    __io_putchar(*ptr++);
  }
  return len;
}
#endif
